package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = dateToList(begin, end);

        String s = StringUtils.join(dateList, ",");

        //计算营业额
        List<Double> turnoverList=new ArrayList<>();
        for(LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            //select sun(amount) from orders where order_time >begin && order_time < end && status = 5
            Double turnover =orderMapper.sumByMap(map);
            turnover =turnover ==null?0.0:turnover;
            turnoverList.add(turnover);
        }
        String s1 = StringUtils.join(turnoverList, ",");


        return TurnoverReportVO.builder()
                .dateList(s)
                .turnoverList(s1)
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = dateToList(begin, end);

        String s = StringUtils.join(dateList, ",");

        List<Integer> newUserList=new ArrayList<>();
        List<Integer> totalUserList=new ArrayList<>();

        for(LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("end",endTime);
            Integer totalUser =userMapper.countByMap(map);
            map.put("begin",beginTime);
            Integer newUser =userMapper.countByMap(map);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        String s1 = StringUtils.join(newUserList, ",");
        String s2 = StringUtils.join(totalUserList, ",");


        return UserReportVO.builder().dateList(s).newUserList(s1).totalUserList(s2).build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = dateToList(begin, end);
        String s = StringUtils.join(dateList, ",");

        //每日订单数 select count(id)  from orders where order_time >begin && order_time < end
        List<Integer> orderCountList=new ArrayList<>();
        //每日有效订单数  select count(id)  from orders where order_time >begin && order_time < end && status = 5
        List<Integer> validOrderCountList=new ArrayList<>();


        for(LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap<>();
            Integer orderCount= getOrderCount(beginTime,endTime,null);
            Integer validOrder=getOrderCount(beginTime,endTime,Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrder);
        }

        //计算时间区间内所有订单数量
        Integer totalOrderCount=orderCountList.stream().reduce(Integer::sum).get();

        //计算时间区间内有效订单数量
        Integer validOrderCount=validOrderCountList.stream().reduce(Integer::sum).get();

        String s1 = StringUtils.join(orderCountList, ",");
        String s2 = StringUtils.join(validOrderCountList, ",");
        Double orderCompletionRate=totalOrderCount!=0?(validOrderCount*1.0/totalOrderCount):0.0;
        return OrderReportVO
                .builder()
                .dateList(s)
                .orderCountList(s1)
                .validOrderCountList(s2)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO salesTop10(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = dateToList(begin, end);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String s = StringUtils.join(names, ",");
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String s1 = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO.builder()
                .nameList(s)
                .numberList(s1)
                .build();
    }

    /**
     * 导出数据
     */
    public void export(HttpServletResponse response) {
        //1.查询数据库，获取营业数据----查询近30天的运营数据
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO=workspaceService.getBusinessData(LocalDateTime.of(beginTime,LocalTime.MIN),LocalDateTime.of(endTime,LocalTime.MAX));

        //2.通过POI把数据写入到Excel中
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模版文件创建一个新的EXcel文件（根据字节流中的数据，在内存中构建一个Excel的对象模型）
            XSSFWorkbook excel = new XSSFWorkbook(stream);
            XSSFSheet sheet = excel.getSheet("sheet1");
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间："+beginTime+"至"+endTime);

            //第4行
            row=sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //第5行
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //第8行开始遍历30天的数据
            for(int i=0;i<30;i++){
                row=sheet.getRow(i+7);
                LocalDateTime begin = LocalDateTime.of(beginTime.plusDays(i), LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(beginTime.plusDays(i), LocalTime.MAX);
                businessDataVO = workspaceService.getBusinessData(begin, end);
                row.getCell(1).setCellValue(beginTime.plusDays(i).toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //3.把Excel文件写入到响应流中
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.close();
            excel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 把日期加入集合
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> dateToList(LocalDate begin, LocalDate end){
        //当前集合用于存放从begin到end的所有日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        return dateList;
    }

    /**
     * 根据条件查询订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status){
        Map map=new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",Orders.COMPLETED);
        return orderMapper.countByMap(map);
    }
}
